package com.hipmarket.platform.security.storage

import com.hipmarket.platform.security.JwtAuthenticationUser
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import java.util.*

abstract class JwtAuthenticationStorage {

    abstract fun findUserByToken(token: String): JwtAuthenticationUser

    abstract fun login(user: JwtAuthenticationUser): String

    abstract fun logout(token: String)

    private val redisKeyPrefix: String
        get() = "jwtToken@"

    protected fun createToken(user: JwtAuthenticationUser, prefix: String = "default"): String {
        val tokenString = prefix + Date().time.toString() + "@" + user.primaryId + randomUUID()
        return redisKeyPrefix + prefix + BCryptPasswordEncoder().encode(tokenString) + randomUUID(1)
    }

    private fun randomUUID (times: Int = 5): String {
        var randomUUID = ""
        var random = if (times > 1) Math.floor(Math.random() * times).toInt() + 1 else 1
        while (random > 0) {
            randomUUID += UUID.randomUUID()
            random -= 1
        }
        return randomUUID
    }

}